/**
 * 前端下载文件
 * @param {string} content 文件内容
 * @param {string} fileName 文件名
 * **/
export function downloadFile (content, fileName) {
  var file = new window.File([content], fileName)
  var a = document.createElement('A')
  var url = URL.createObjectURL(file)

  a.href = url
  a.download = fileName
  a.style.display = 'none'
  a.click()

  setTimeout(function () {
    URL.revokeObjectURL(url)
    a.remove()
  }, 1000)
}

/**
 * 读取一个文件对象的内容
 * @param {File|Blob} blob 文件对象
 * @param {(err, data) => void} cb 回调
 * **/
export function blob2Text (blob, cb) {
  if (!(blob instanceof window.Blob)) return cb(new Error('必须是Blob对象'))

  if (blob.text) {
    blob.text().then(function (data) { cb(null, data) }).catch(function (err) { cb(err) })
  } else {
    var read = new window.FileReader()
    read.readAsText(blob, 'utf8')
    read.onloadend = function () {
      if (read.error) {
        cb(read.error)
      } else {
        cb(read.result)
      }
    }
  }
}

/**
 * 通过video标签获取视频元数据
 * @param {string} url - 视频连接
 * @param {function} cb(err, data) - 回调
 * **/
export function getVideoMetadataByVideoElemet (url, cb) {
  var v = document.createElement('video')
  v.src = url
  v.style.display = 'none'

  v.addEventListener('loadedmetadata', function () {
    cb && cb(null, {
      duration: v.duration,
      w: v.videoWidth,
      h: v.videoHeight,
      video: v
    })
  })

  v.addEventListener('error', function () {
    cb && cb(v.error)
    v.remove()
  })

  document.body.appendChild(v)
}
